package offerbook;

import java.util.ArrayList;

/**
 * 顺时针打印矩阵
 * @date 2020/3/9 15:29
 */
public class Code20_PrintMatrix {
    public static ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> list = new ArrayList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return list;
        }
        int aRow = 0,aCol = 0;
        int bRow = matrix.length-1,bCol = matrix[0].length - 1;
        while (aRow <= bRow && aCol <= bCol){
            print(matrix,aRow++,aCol++,bRow--,bCol--,list);
        }
        return list;
    }
    private static void print(int[][]m,int aRow,int aCol,int bRow,int bCol,
                              ArrayList<Integer> list){
        if(aRow == bRow){
            for (int i = aCol; i <= bCol ; i++) {
                list.add(m[aRow][i]);
            }
            return;
        }
        if(aCol == bCol){
            for (int i = aRow; i <=bRow ; i++) {
                list.add(m[i][aCol]);
            }
            return;
        }
        for (int i = aCol; i < bCol ; i++) {
            list.add(m[aRow][i]);
        }
        for (int i = aRow; i < bRow; i++) {
            list.add(m[i][bCol]);
        }
        for (int i = bCol; i > aCol ; i--) {
            list.add(m[bRow][i]);
        }
        for (int i = bRow; i > aRow; i--) {
            list.add(m[i][aCol]);
        }
    }

    public static void main(String[] args) {
        int[][] m = {{1, 2, 3, 4, 0}, {5, 6, 7, 8, 0}, {9, 10, 11, 12, 0},
                {13, 14, 15, 16, 0}};
        ArrayList<Integer> list = printMatrix(m);
        for (Integer integer : list) {
            System.out.print(integer+"  ");
        }
    }
}
